<template>
  <div class="article-container">
    <!--数据表格-->
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="文章列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @emptyQuery="emptyQuery" @receiveKeyword="receiveKeyword">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container"
                   @mouseenter="showEditorContainer"
                   @mouseleave="hideEditorContainer"
                   v-if="hasPermission('article:insert')">
                <!--按钮-->
                <el-button class="toolbar-button">
                  <i class="iconfont icon-combinedshapecopy2"></i>
                  撰写文章
                </el-button>
                <!--悬停时显示的菜单-->
                <div class="editor-container" ref="editorContainer" v-if="hasPermission('article:insert')">
                  <ul>
                    <li class="editor-item blank-item"></li>
                    <router-link tag="li" class="editor-item" to="/dashboard/article/richeditor">使用富文本编辑器</router-link>
                    <router-link tag="li" class="editor-item" to="/dashboard/article/markdown">使用markdown编辑器
                    </router-link>
                  </ul>
                </div>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('article:update')">
                <el-button @click="batchRelease" class="toolbar-button">
                  <i class="iconfont icon-fabu-"></i>
                  批量发布
                </el-button>
              </div>
              <!--工具栏上第三个按钮-->
              <div class="btn-container" v-if="hasPermission('article:update')">
                <el-button @click="batchUnrelease" class="toolbar-button">
                  <i class="iconfont icon-xiajia"></i>
                  批量下架
                </el-button>
              </div>
              <!--工具栏上第四个按钮-->
              <div class="btn-container" v-if="hasPermission('article:update')">
                <el-button @click="batchDelete" class="toolbar-button">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>
            <div slot="customContainer" class="custom-container">
              <el-select v-model="query.cid" size="small" class="category-select" placeholder="分类查询">
                <el-option
                  v-for="item in categoryData"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </tool-bar>
          <!--表格-->
          <el-table
            slot="content"
            ref="articleTable"
            class="article-table"
            :data="articleData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectArticle"
            @select-all="selectArticle"
            :key="tableKey">
            <el-table-column
              type="selection"
              min-width="55"
              align="center">
            </el-table-column>
            <el-table-column
              prop="title"
              label="文章标题"
              min-width="180">
            </el-table-column>
            <el-table-column
              align="center"
              prop="categoryName"
              label="文章分类"
              min-width="40">
            </el-table-column>
            <el-table-column
              align="center"
              prop="isRelease"
              label="发布"
              min-width="40">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isRelease"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('article:update')"
                  @change="changeIsRelease(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="canComment"
              label="评论"
              min-width="40">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.canComment"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('article:update')"
                  @change="changeCanComment(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="upToTop"
              label="置顶"
              min-width="40">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.upToTop"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('article:update')"
                  @change="changeUpToTop(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="browseCount"
              label="浏览"
              min-width="25">
            </el-table-column>
            <el-table-column
              align="center"
              prop="commentCount"
              label="评论"
              min-width="25">
            </el-table-column>
            <el-table-column
              align="center"
              prop="preferCount"
              label="点赞"
              min-width="25">
            </el-table-column>
            <el-table-column
              prop="releaseTime"
              label="发布时间"
              min-width="80">
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="80">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="80">
              <template slot-scope="scope">
                <span v-if="!hasPermission('article:update') && !hasPermission('article:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  @click="handleEdit(scope.$index, scope.row)" v-if="hasPermission('article:update')">编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)" v-if="hasPermission('article:delete')">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <!--分页插件-->
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar';

  import {
    getArticleByPage,
    changeArticleStatus, changeMultiArticleStatus, deleteByIds
  } from "../../network/viewsRequest/article";
  import {getAllCategory} from "../../network/viewsRequest/category";
  import {hasPermission} from "../../common/permission";

  import {WRITTEN_BY_RICHEDITOR} from "../../common/const";

  export default {
    name: 'ArticleView',
    data() {
      return {
        query: { // 查询条件都放这里边
          keyword: '', // toolbar中传递过来的搜索关键字
          cid: null, // select中的搜索分类
          currentPage: 1, // 当前页
          pageSize: 10, // 一页显示几条数据
        },
        articleData: [], // 文章的数据
        categoryData: [], // 分类的数据
        multiSelections: [], // 多选的集合
        total: 0, // 总数据量
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 初始化查询条件
       */
      emptyQuery() {
        let currentPage = this.query.currentPage;
        let pageSize = this.query.pageSize;
        this.query = {
          keyword: '',
          cid: null,
          currentPage: currentPage,
          pageSize: pageSize,
        }
        this.loadTableForArticle();
      },
      /**
       * 获取所有的分类信息
       */
      getAllCategory() {
        getAllCategory().then(res => {
          if (res.code == 1) {
            this.categoryData = res.data;
          } else {
            this.categoryData = [];
          }
        })
      },
      /**
       * 获取table的数据
       */
      loadTableForArticle() {
        getArticleByPage(this.query).then(res => {
          if (res.code == 1) {
            this.articleData = res.data.items;
            this.total = res.data.total;
          } else {
            this.articleData = [];
            this.total = 0;
          }
        });
      },
      /**
       * 点击多选框时触发的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectArticle(selection, row) {
        // 将选择的文章信息保存到multiSelections中去
        this.multiSelections = selection;
      },
      /**
       * 接收子组件toolbar传递过来的搜索关键字keyword
       * @param keyword 搜索关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadTableForArticle();
      },
      /**
       * 用户在点击分页插件时，获取用户点击到的是第几页
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        this.loadTableForArticle();
      },
      /**
       * 当输入移入`撰写文章`按钮时，显示相应的菜单
       */
      showEditorContainer() {
        let editorContainer = this.$refs.editorContainer;
        editorContainer.style.display = 'block';
      },
      /**
       * 当输入移出`撰写文章`按钮时，隐藏相应的菜单
       */
      hideEditorContainer() {
        let editorContainer = this.$refs.editorContainer;
        editorContainer.style.display = 'none';
      },
      /**
       * 编辑文章
       * @param index 当前编辑文章的索引
       * @param row 当前编辑文章的那行内容
       */
      handleEdit(index, row) {
        // 根据编辑器的不同跳转到相应的页面
        if (row.editorType == WRITTEN_BY_RICHEDITOR) {
          this.$router.push("/dashboard/article/richeditor?id=" + row.id);
        } else {
          this.$router.push("/dashboard/article/markdown?id=" + row.id);
        }
      },
      /**
       * 点击文章后面的`删除`按钮，删除单篇文章文章
       * @param index 需要删除文章的索引
       * @param row 需要删除文章的那行内容
       */
      handleDelete(index, row) {
        let delIds = [];
        delIds.push(row.id);
        // 调用方法删除该条记录
        this.deleteArticles(delIds)
      },
      /**
       * 用于删除文章的方法的具体逻辑
       * @param ids 需要删除文章的id的集合
       */
      deleteArticles(ids) {
        this.$confirm('是否要删除？注意：一旦删除无法恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteByIds(ids.join(",")).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
            // 刷新父组件中表格的数据
            this.loadTableForArticle();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除操作已经被取消'
          })
        })
      },
      /**
       * 切换文章是否发布
       * 另外如果一篇文章被设置为'未发布'，那么它对应的'允许评论'和'文章置顶'都要改为false
       * @param row 表格中的行数据，即一篇文章的数据
       */
      changeIsRelease(row) {
        // row.isRelease中保存的是切换后的值
        if (row.isRelease == 0) {
          changeArticleStatus(row.id, {isRelease: row.isRelease, canComment: 0, upToTop: 0}).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
              this.loadTableForArticle();
            }

          });
        } else {
          changeArticleStatus(row.id, {isRelease: row.isRelease}).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
              this.loadTableForArticle();
            }
          });
        }

      },
      /**
       * 切换文章是否允许评论
       * @param row 操作的文章对应的数据
       */
      changeCanComment(row) {
        changeArticleStatus(row.id, {canComment: row.canComment}).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
            this.loadTableForArticle();
          }
        });
      },
      /**
       * 切换文章是否置顶
       * @param row 操作的文章对应的数据
       */
      changeUpToTop(row) {
        changeArticleStatus(row.id, {upToTop: row.upToTop}).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
            this.loadTableForArticle();
          }
        });
      },
      /**
       * 检查用户有没有进行了选择
       */
      checkSelected() {
        if (this.multiSelections.length == 0) {
          this.$message({
            type: 'error',
            message: '请先选择需要操作的记录！'
          });
          return false;
        }
        return true;
      },
      /**
       * 批量发布文章
       */
      batchRelease() {
        // 判断有没有选择
        // 1.检查用户有没有选择记录
        if (!this.checkSelected()) {
          return false;
        }
        // 2.过滤掉已经是发布状态的文章
        let ids = [];
        for (let selection of this.multiSelections) {
          if (selection.isRelease == 0) {
            ids.push(selection.id);
          }
        }
        if (ids.length == 0) {
          this.$message.error("所选的文章都已经启用，不能再次启用");
          return false;
        }
        // 3.进行修改
        this.$confirm("是否要进行批量启用文章？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(() => {
          changeMultiArticleStatus(ids.join(","), {isRelease: 1}).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '批量发布成功'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
            this.loadTableForArticle();
          })
        }).catch(() => {
          this.$message.info("操作已经被取消");
        })
      },
      /**
       * 批量下架文章
       */
      batchUnrelease() {
        // 1.检查用户有没有选择记录
        if (!this.checkSelected()) {
          return false;
        }
        // 2.过滤掉已经是下架状态的文章
        let ids = [];
        for (let selection of this.multiSelections) {
          if (selection.isRelease == 1) {
            ids.push(selection.id);
          }
        }
        if (ids.length == 0) {
          this.$message.error("所选的文章都已经下架，不能再次下架");
          return false;
        }
        // 3.进行修改
        this.$confirm("是否要进行批量下架文章？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(() => {
          changeMultiArticleStatus(ids.join(","), {isRelease: 0, canComment: 0, upToTop: 0}).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '批量下架成功'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
            this.loadTableForArticle();
          });
        }).catch(() => {
          this.$message.info("操作已经被取消");
        })
      },
      /**
       * 批量删除文章
       */
      batchDelete() {
        // 1.检查用户有没有选择记录
        if (!this.checkSelected()) {
          return false;
        }
        // 2.进行删除
        let delIds = this.multiSelections.map(item => {
          return item.id;
        });
        // 调用方法删除指定的所有记录
        this.deleteArticles(delIds)
      },
    },
    mounted() {
      // 页面初始化时获取文章的数据填充表格
      this.loadTableForArticle();
      // 页面初始化时获取分类的数据填充select
      this.getAllCategory();
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.articleData.length; i++) {
          key += this.articleData[i].updateTime;
        }
        return key;
      }
    },
    components: {
      Card,
      Pagination,
      ToolBar
    }
  }
</script>

<style scoped>

  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }

  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
    display: inline-block !important;
    vertical-align: bottom;
    position: relative;
  }

  .button-all-container {
    display: inline-block;
    vertical-align: bottom;
  }

  .custom-container {
    display: inline-block;
    margin-left: 10px
  }

  .el-card {
    margin-top: 30px;
  }

  .editBtn {
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff
  }

  .el-select {
    width: 110px;
  }

  .btn-container {
    margin-right: 5px;
  }

  .category-select {
    margin-right: 5px;
  }

</style>

<style>

  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 12px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-input--small .el-input__inner {
    height: 36px;
  }

  .el-select-dropdown__wrap, .el-scrollbar__wrap {
    margin-bottom: 0px !important
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
